import { CloseOutlined } from '@ant-design/icons';
import { Modal, ModalProps, Button, Avatar, Spin } from 'antd';
import React, { useEffect } from 'react';

import useWindowWidth from '@/hooks/event/use-window-width';
import { SvgIcon } from '../icon';

export interface MyModalProps extends ModalProps {
  iconSrc?: string;
  iconColor?: string;
  title?: any;
  isCentered?: boolean;
  isLoading?: boolean;
  isOpen?: boolean;
  onClose?: () => void;
  closeOnOverlayClick?: boolean;
  size?: 'md' | 'lg';
  w?: any;
  minW?: string | string[];
  maxW?: any;
}

function MyModal({
  isOpen = false,
  onClose,
  iconSrc = 'menu_set',
  title,
  children,
  isCentered,
  isLoading,
  width = 'auto',
  closeOnOverlayClick = true,
  iconColor,
  size = 'md',
  w,
  minW = ['90vw', '900px'],
  maxW,
  ...props
}: MyModalProps) {
  const { isPc } = useWindowWidth();

  const modalWidth = size === 'md' ? 400 : 600;

  // 计算最终宽度，优先级：w > width > 根据size的默认值
  const baseWidth = w || width || modalWidth;

  // 获取最小宽度的移动端和PC端值
  const mobileMinWidth = Array.isArray(minW) ? minW[0] : minW;
  const pcMinWidth = Array.isArray(minW) ? minW[1] : minW;

  // 根据设备类型确定响应式宽度
  const responsiveWidth = isPc ? pcMinWidth : mobileMinWidth;

  // 设置样式，包括最小宽度和最大宽度
  const contentStyle = {
    maxHeight: '85vh',
    // boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
    minWidth: isPc ? pcMinWidth : mobileMinWidth,
    maxWidth: maxW,
    position: 'relative' as const,
  };

  return (
    <Modal
      open={isOpen}
      onCancel={() => onClose && onClose()}
      centered={isPc ? isCentered : true}
      footer={null}
      maskClosable={closeOnOverlayClick}
      width={responsiveWidth}
      closeIcon={!title && onClose ? <CloseOutlined /> : null}
      style={contentStyle}
      destroyOnClose
      title={
        title ? (
          <div className="flex items-center border-b border-[#F4F6F8] bg-[#FBFBFC] py-2">
            {iconSrc && (
              <SvgIcon
                style={{ color: iconColor, objectFit: 'contain', width: '1.5rem', borderRadius: 2 }}
                icon={iconSrc}
              />
            )}
            <div className="ml-2 font-medium text-[#333]">{title}</div>
            <div className="flex-1" />
            {onClose && (
              <Button
                type="text"
                size="small"
                icon={<CloseOutlined />}
                onClick={() => onClose()}
                className="relative"
              />
            )}
          </div>
        ) : null
      }
      {...props}
    >
      <Spin spinning={!!isLoading}>
        <div className="flex h-full flex-col overflow-auto">{children}</div>
      </Spin>
    </Modal>
  );
}

export default MyModal;
